package org.kugua.strategy;

import lombok.extern.slf4j.Slf4j;
import org.kugua.context.CaptchaContext;
import org.kugua.effect.IEffect;
import org.kugua.image.ImageSelector;
import org.kugua.image.impl.MemoryBgImageSelector;
import org.kugua.utils.ImageUtils;
import org.springframework.util.CollectionUtils;

import java.awt.image.BufferedImage;
import java.util.Collections;
import java.util.List;

@Slf4j
public abstract class AbstractSliderCaptchaStrategy extends ParentCaptchaStrategy {

    /**
     * 验证码效果
     */
    @Override
    public List<IEffect> getEffects() {
        return Collections.emptyList();
    }

    /**
     * 图片选择器
     */
    private ImageSelector<BufferedImage> imageSelector = new MemoryBgImageSelector();

    public ImageSelector<BufferedImage> getImageSelector() {
        return imageSelector;
    }

    public void setImageSelector(ImageSelector<BufferedImage> imageSelector) {
        this.imageSelector = imageSelector;
    }

    /**
     * 图片过大时，最大选取1部分，进行缩放
     *
     * @param context 上下文信息
     * @return BufferedImage
     */
    protected BufferedImage selectImageIfNeedScale(CaptchaContext context) {
        BufferedImage originalImage = imageSelector.select();
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        boolean isScale = width > context.getWidth() || height > context.getHeight();
        if (isScale) {
            return ImageUtils.scaleImage(originalImage, context.getWidth(), context.getHeight());
        }
        return originalImage;
    }


    /**
     * 验证码是否有效
     *
     * @param source   原始值
     * @param target   目标值
     * @param accuracy 精度
     * @return boolean true：正确，否则false
     */
    @Override
    public boolean valid(List<String> source, List<String> target, Long accuracy) {
        if (CollectionUtils.isEmpty(target) || source.size() != target.size()) {
            return false;
        }
        try {
            Double sourcePositionX = Double.parseDouble(source.get(0));
            Double targetPositionY = Double.parseDouble(target.get(0));
            return Math.abs(sourcePositionX - targetPositionY) <= accuracy;
        } catch (Exception e) {
            log.error("slider captcha valid failed.");
            return false;
        }
    }
}
